package com.rainwen.shiro.controller;

import com.rainwen.shiro.entity.SysUser;
import com.rainwen.shiro.page.PageRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;

/**
 * @author rain.wen
 * @date 2018/1/16.
 */
public class BaseController {

    protected SysUser getUser() {
        Subject subject = SecurityUtils.getSubject();
        if(subject != null) {
            SysUser user = (SysUser) subject.getPrincipals().asList().get(1);
            return user;
        }
        return null;
    }

    protected Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        if(subject != null) {
            SysUser user = (SysUser) subject.getPrincipals().asList().get(1);
            return user.getId();
        }
        return null;
    }

    protected String getUsername() {
        Subject subject = SecurityUtils.getSubject();
        if(subject != null) {
            SysUser user = (SysUser) subject.getPrincipals().asList().get(1);
            return user.getUsername();
        }
        return "";
    }

    /**
     * 分页参数
     *
     * @param request
     * @return
     */
    protected PageRequest setPageRequest(HttpServletRequest request) {
        String number = request.getParameter("number");
        String size = StringUtils.isNotEmpty(request.getParameter("size")) ? request.getParameter("size") : "10";
        PageRequest page = new PageRequest((StringUtils.isEmpty(number) ? 0 : Integer.parseInt(number) - 1), Integer.parseInt(size));
        return page;
    }
}
